import Vue from 'vue'
import Router from 'vue-router'
import Manage from '../pages/Manage.vue'
import Login from '../pages/Login.vue'
import Register from '../pages/Register.vue'
import NoFound from '../pages/404.vue'

Vue.use(Router)

// 解决一个bug
const originalPush = Router.prototype.push
Router.prototype.push = function push(location) {
  return originalPush.call(this, location).catch(err => err)
}


const routes = [
  {
    path: '/login',
    name: 'login',
    component: Login
  },
  {
    path: '/',
    redirect: '/login'
  },
  {
    path: '/register',
    name: 'register',
    component: Register
  },

  {
    path: '/404',
    name: '404',
    component: NoFound
  },
  {
    path: '*',
    redirect: '/404'
  },

];

const router = new Router({
  routes
})

//重置路由
export const resetRouter = () => {
  router.matcher = new Router({
    mode: 'history',
    routes
  })
}

// 注意：刷新页面会导致页面路由重置
export const setRoutes = () => {
  const storeMenus = localStorage.getItem("menus");
  if (storeMenus) {
    // 拼装动态路由
    const manageRoute = {
      path: '/', name: 'Manage', component: Manage,
      children: [{ path: 'person', name: 'Person', component: () => import('../pages/Person.vue'), meta: { title: '个人信息' } }], meta: { title: '' }
    }
    const menus = JSON.parse(storeMenus);
    menus.forEach(item => {
      if (item.path) {  // 当且仅当path不为空的时候才去设置路由
        let itemMenu = { path: item.path.replace("/", ""), name: item.pagePath, component: () => import('../pages/' + item.pagePath + '.vue'), meta: { title: item.name } };
        manageRoute.children.push(itemMenu)
      } else if (item.children.length) {
        item.children.forEach(item => {
          if (item.path) {
            let itemMenu = { path: item.path.replace("/", ""), name: item.pagePath, component: () => import('../pages/' + item.pagePath + '.vue'), meta: { title: item.name } }
            manageRoute.children.push(itemMenu)
          }
        })
      };
      if (item.name === '系统管理') {
        manageRoute.children.push({ path: 'goods/details', name: 'GoodDetail', component: () => import('../pages/GoodDetail.vue'), meta: { title: '商品操作' } })
      }
    })

    // 获取当前的路由对象名称数组
    const currentRouteNames = router.getRoutes().map(v => v.name)
    // 动态添加到现在的路由对象中去
    if (!currentRouteNames.includes('Person')) {//去除重复添加
      router.addRoute(manageRoute)
    }
  }
}

// 重置我就再set一次路由,刷新浏览器也会触发添加
setRoutes()

// router.beforeEach((to, from, next) => {
//   localStorage.setItem("currentPathName", to.name)  // 设置当前的路由名称
//   store.commit("setPath")
//   next()
// })

export default router
